package com.annet.token.config.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 多数据源配置
 *
 * @author dingjb
 * @date 2020/12/31
 */
@ConditionalOnProperty(prefix = "annet.token",name = "security.type",havingValue = "jpa")
@Slf4j
@Configuration
public class DataSourceConfig {

    @Bean(name = "securityDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.security")
    public DataSource securityDataSource() {
        return DataSourceBuilder.create()
//                .url("jdbc:mysql://61.133.204.114:9990/annet_security?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai")
//                .username("root")
//                .password("Annet@Yankang@2020")
//                .driverClassName("com.mysql.cj.jdbc.Driver")
                .build();
    }


    /**
     * 显示数据库连接池信息
     *
     * @param dataSource
     */
    public static void logDS(DataSource dataSource) {
        HikariDataSource hds = (HikariDataSource) dataSource;
        String info = "\n\n\tHikariCP连接池配置\n\t连接池名称：" +
                hds.getPoolName() + "外部数据库连接"+
                "\n\t最小空闲连接数：" +
                hds.getMinimumIdle() +
                "\n\t最大连接数：" +
                hds.getMaximumPoolSize() +
                "\n\t连接超时时间：" +
                hds.getConnectionTimeout() +
                "ms\n\t空闲连接超时时间：" +
                hds.getIdleTimeout() +
                "ms\n\t连接最长生命周期：" +
                hds.getMaxLifetime() +
                "ms\n";
        log.info(info);
    }
}